package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.dto.UserRegDTO;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        /**
         * 注册功能需要实现
         * 1.用户名占用功能
         * 2.检验
         * 3.插入数据库功能
         */
        String username = userRegDTO.getUsername();
        UserVO userVO= userMapper.selectByUsername(username);
        if(userVO != null){
            return 2;
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;

    }

    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, HttpSession session){

        /**
         * 登录功能：
         * 1.查用户名存在
         * 2.查密码正确
         */
        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if(userVO == null){ //查用户名
            return 3;
        }

        String password = userLoginDTO.getPassword();
        if(password.equals(userVO.getPassword())){  //查密码匹配
            session.setAttribute("user",userVO); //存入session
            return 1;
        }

        return 2;

    }

    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){

        /**
         * 登入状态
         * 1.看session数据库是否有key
         */
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    @GetMapping("logout")
    public String logout(HttpSession session){

        /**
         * 登出状态
         * 1.删除session数据库内key
         */
        session.removeAttribute("user");
        return "登出成功";
    }


}
